import com.fasterxml.jackson.databind.ObjectMapper;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/json")
public class GetBodyJsonParameterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 此处约定请求：
        // Post / Json
        // content-Type: application/json
        //
        //{
        //     userName:"llt"
        //     password:"2569"
        //}

        // 响应也按照json
        //{
        // ok: true
        //}

        // 将请求的 body 按照 json 格式转成 java 对象
        ObjectMapper objectMapper = new ObjectMapper();
        Request request = objectMapper.readValue(req.getInputStream(), Request.class);
        System.out.println("userName=" + request.userName);
        System.out.println("passWord=" + request.passWord);

        // 将 java 对象 转换为 json 字符串
        Response response = new Response();
        response.ok = true;
        String resJson = objectMapper.writeValueAsString(response);
        resp.getWriter().write(resJson);
    }
}
